package pyip.lib.javalearn.classloader.load.rule;

import java.net.MalformedURLException;

/**
 * 如果ClassA是由某个ClassLoader加载的，那么ClassA中依赖的需要加载的类，默认也会由同一个ClassLoader加载。
 */
public class UseParentClassClassLoaderDemo {

    public static void main(String[] args) throws MalformedURLException, ClassNotFoundException {
        System.out.println("MainClass getClassLoader --- " + UseParentClassClassLoaderDemo.class.getClassLoader());
        System.out.println("MainClass getContextClassLoader --- " + Thread.currentThread().getContextClassLoader());
        new InnerThread11().start();
    }

}

class InnerThread11 extends Thread {
    @Override
    public void run() {
        try {
            System.out.println();
            // 加载, 但没有初始化
            System.out.println("InnerThread1 A.class.getClassLoader() --- " + A.class.getClassLoader());

            // 改变 contextClassLoader
            MyClassLoader myClassLoader = new MyClassLoader();
            Thread.currentThread().setContextClassLoader(myClassLoader);
            System.out.println("InnerThread1 setContextClassLoader(myClassLoader)");
            System.out.println("InnerThread1 getContextClassLoader --- " + Thread.currentThread().getContextClassLoader());

            A a2 = new A();
            System.out.println("InnerThread1 new A, A.class.getClassLoader() --- " + A.class.getClassLoader());
            a2.doNothing();

            // Class<?> contextClazz = Class.forName("pyip.lib.javalearn.classloader.load.rule.A", true, myClassLoader);
            Class<?> contextClazz = Class.forName("pyip.lib.javalearn.classloader.load.rule.A");
            // contextClazz == A.class
            System.out.println("InnerThread1 Class.forName A, A.class.getClassLoader() --- " + contextClazz.getClassLoader());

            Thread innerThread2 = new InnerThread12();
            innerThread2.start();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class InnerThread12 extends Thread {
    @Override
    public void run() {
        System.out.println();
        System.out.println("InnerThread2 getContextClassLoader --- " + Thread.currentThread().getContextClassLoader());
        // try {
        // ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        // Class<?> clazzB = classLoader.loadClass("pyip.lib.javalearn.classloader.load.rule.B");
        // System.out.println("InnerThread2 getClassLoader --- " + clazzB.getClassLoader());
        // } catch (ClassNotFoundException e) {
        // e.printStackTrace();
        // }

        B b = null;
        // b = new B();
        try {
            b = (B) Class.forName("pyip.lib.javalearn.classloader.load.rule.B").newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("InnerThread2 b.getClass().getClassLoader() --- " + b.getClass().getClassLoader());
    }
}
